package com.eagle.epay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eagle.epay.common.ResultVO;
import com.eagle.epay.entity.Category;
import com.eagle.epay.entity.Product;
import com.eagle.epay.mapper.ProductMapper;
import com.eagle.epay.service.ICategoryService;
import com.eagle.epay.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eagle.epay.util.ResultVOUtil;
import com.eagle.epay.vo.ProductVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author eagle
 * @since 2019-12-21
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

	@Autowired
	ICategoryService categoryService;
	@Override
	public ResultVO<PageInfo>  listProductsById(Integer categoryId, int pageNum, int pageSize) {
		QueryWrapper<Product> wrapper = new QueryWrapper<>();
		if(null != categoryId){
			Set<Integer> categoryByIds =
					categoryService.getCategoryById(categoryId);
			categoryByIds.add(categoryId);
			wrapper.in("category_id", categoryByIds);
		}
		PageHelper.startPage(pageNum, pageSize);
		List<Product> productList = this.list(wrapper);
		List<ProductVo> productVoList = productList.stream().map(this::copy).collect(Collectors.toList());
		PageInfo pageInfo = new PageInfo<>(productList);
		pageInfo.setList(productVoList);
		return ResultVOUtil.success(pageInfo);
	}

	private ProductVo copy(Product source){
		ProductVo target = new ProductVo();
		BeanUtils.copyProperties(source,target);
		return target;
	}
}
